<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>学生主页 - 课程表</title>
    <!-- 引入 Vue 3 全局构建版 -->
    <script src="js/vue.global.js"></script>
    <!-- 引入 Axios 用于 HTTP 请求 -->
    <script src="js/axios.min.js"></script>
    <!-- 引入 Element Plus 样式 -->
    <link rel="stylesheet" href="css/index.css">
    <!-- 引入 Element Plus 组件库（完整版） -->
    <script src="js/index.full.js"></script>
    <!-- 引入自定义 CSS -->
    <link rel="stylesheet" href="css/home.css">
</head>
<body>
<div id="app" class="container">
    <!-- 顶部标题区域：显示用户名 + 设置按钮 -->
    <div class="header">
        <div class="title">{{ username }} 的课程表</div>
        <el-button type="primary" size="small" @click="openSettings">⚙️ 设置</el-button>
    </div>

    <!-- 当前查看的周信息，点击可切换查看其他周 -->
    <div class="week-info" @click="openViewWeekDialog">
        第 <span>{{ viewWeek }}</span> 周（{{ weekDateRange }}）
        <!-- 如果不是系统当前周，显示提示 -->
        <span v-if="viewWeek !== systemCurrentWeek" class="non-current-week">（非本周）</span>
    </div>

    <!-- 课程表主体：表格形式展示每天每节课 -->
    <table>
        <thead>
        <tr>
            <!-- 第一列为空（用于显示时间段） -->
            <th></th>
            <!-- 动态生成周一至周日的表头，包含日期 -->
            <th v-for="(date, index) in dayHeaders" :key="index">
                周{{ ['一','二','三','四','五','六','日'][index] }}<br/>
                <small>{{ date }}</small> <!-- 显示具体月/日 -->
            </th>
        </tr>
        </thead>
        <tbody>
        <!-- 遍历时间段（共12行，含午休、晚饭等非课程时段） -->
        <tr v-for="(time, index) in timeSlots" :key="index">
            <!-- 左侧显示时间段 -->
            <td class="time-slot">{{ time }}</td>
            <!-- 右侧7列：周一到周日 -->
            <td
                    v-for="day in 7"
                    :key="day"
                    class="course-cell"
                    @click="showCourseDetail(timetable[index][day - 1])"
            >
            <!-- 如果该时段有课，显示课程名和地点 -->
            <div v-if="timetable[index][day - 1]">
                <div class="course-name">{{ timetable[index][day - 1].name }}</div>
                <div class="course-location">{{ timetable[index][day - 1].location }}</div>
            </div>
            <!-- 无课则显示“—” -->
            <div v-else style="color: #ccc;">—</div>
            </td>
        </tr>
        </tbody>
    </table>

    <!-- 课程详情弹窗（原生 modal，非 Element Plus） -->
    <div class="modal" id="courseModal" @click="closeModal">
        <div class="modal-content" @click.stop> <!-- 阻止点击内容区域关闭弹窗 -->
            <span class="close" @click="closeModal">&times;</span>
            <h3>{{ selectedCourse?.name }}</h3>
            <p><strong>教师：</strong>{{ selectedCourse?.teacher || '—' }}</p>
            <p><strong>学分：</strong>{{ selectedCourse?.credit || '—' }}</p>
            <p><strong>地点：</strong>{{ selectedCourse?.location || '—' }}</p>
            <p><strong>时间：</strong>
                周{{ ['','一','二','三','四','五','六','日'][selectedCourse?.dayOfWeek] }}
                {{ selectedCourse?.startTime }} - {{ selectedCourse?.endTime }}
            </p>
            <p><strong>周类型：</strong>
                {{ {0: '每周', 1: '单周', 2: '双周'}[selectedCourse?.weekType] || '每周' }}
            </p>
            <p><strong>描述：</strong>{{ selectedCourse?.description || '—' }}</p>

            <!-- 操作按钮：编辑 / 删除 -->
            <div style="margin-top: 20px; text-align: right;">
                <el-button size="small" @click="openEditFromDetail">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCourse">删除</el-button>
            </div>
        </div>
    </div>

    <!-- 添加/编辑课程的对话框（使用 Element Plus Dialog） -->
    <el-dialog
            :title="isEditing ? '编辑课程' : '添加课程'"
            v-model="formVisible"
            width="500px"
    >
        <el-form :model="courseForm" label-width="80px">
            <el-form-item label="课程名称" required>
                <el-input v-model="courseForm.name" placeholder="请输入课程名称" />
            </el-form-item>
            <el-form-item label="教师">
                <el-input v-model="courseForm.teacher" placeholder="请输入教师姓名" />
            </el-form-item>
            <el-form-item label="学分">
                <el-input-number v-model="courseForm.credit" :min="0" :max="10" />
            </el-form-item>
            <el-form-item label="星期" required>
                <el-select v-model="courseForm.dayOfWeek" placeholder="请选择星期">
                    <el-option
                            v-for="d in 7"
                            :key="d"
                            :label="'周' + ['','一','二','三','四','五','六','日'][d]"
                            :value="d"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="上课时间" required>
                <el-select v-model="courseForm.timeSlot" placeholder="请选择时间段">
                    <el-option
                            v-for="item in timeOptions"
                            :key="item.start"
                            :label="item.label"
                            :value="item.label"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="地点" required>
                <el-input v-model="courseForm.location" placeholder="例如：教1-101" />
            </el-form-item>
            <el-form-item label="周类型">
                <el-radio-group v-model="courseForm.weekType">
                    <el-radio :label="0">每周</el-radio>
                    <el-radio :label="1">单周</el-radio>
                    <el-radio :label="2">双周</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="描述">
                <el-input
                        type="textarea"
                        v-model="courseForm.description"
                        placeholder="可选，课程简介或备注"
                        :rows="3"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="formVisible = false">取消</el-button>
            <el-button type="primary" @click="saveCourse">保存</el-button>
        </template>
    </el-dialog>

    <!-- 查看任意周的对话框 -->
    <el-dialog title="查看周次" v-model="viewWeekDialogVisible" width="300px">
        <el-radio-group v-model="selectedViewWeek" style="display: flex; flex-direction: column;">
            <el-radio v-for="w in 18" :key="w" :label="w">第 {{ w }} 周</el-radio>
        </el-radio-group>
        <template #footer>
            <el-button @click="viewWeekDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmViewWeek">确定</el-button>
        </template>
    </el-dialog>

    <!-- 设置菜单对话框 -->
    <el-dialog title="系统设置" v-model="settingsVisible" width="320px">
        <div class="setting-item" @click="handleSetting('add')">
            <i>➕</i> 添加课程
        </div>
        <div class="setting-item" @click="handleSetting('setWeek')">
            <i>📅</i> 设置当前周
        </div>
        <div class="setting-item" @click="handleSetting('logout')" style="border-top: 1px solid #eee; margin-top: 10px; color: #ff4d4f;">
            <i>🚪</i> 切换账号
        </div>
    </el-dialog>

    <!-- 设置当前周对话框 -->
    <el-dialog title="设置当前周" v-model="setCurrentWeekVisible" width="300px">
        <p>今天（{{ todayDate }}）是第几周？</p>
        <el-radio-group v-model="selectedCurrentWeek" style="display: flex; flex-direction: column; margin-top: 10px;">
            <el-radio v-for="w in 18" :key="w" :label="w">第 {{ w }} 周</el-radio>
        </el-radio-group>
        <template #footer>
            <el-button @click="setCurrentWeekVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSetCurrentWeek">确定</el-button>
        </template>
    </el-dialog>
</div>

<script>
    // 从 Vue 中解构常用 API
    const { createApp, ref, computed, onMounted } = Vue;
    // 从 Element Plus 中解构消息提示组件
    const { ElMessage } = ElementPlus;

    // 创建 Vue 应用
    const app = createApp({
        setup() {
            // ========== 预定义时间段 ==========
            // 用于下拉选择的时间段选项（带 start/end 便于后端处理）
            const timeOptions = ref([
                { label: '08:30-09:15', start: '08:30', end: '09:15' },
                { label: '09:25-10:10', start: '09:25', end: '10:10' },
                { label: '10:30-11:15', start: '10:30', end: '11:15' },
                { label: '11:25-12:10', start: '11:25', end: '12:10' },
                { label: '14:00-14:45', start: '14:00', end: '14:45' },
                { label: '14:55-15:40', start: '14:55', end: '15:40' },
                { label: '16:00-16:45', start: '16:00', end: '16:45' },
                { label: '16:55-17:40', start: '16:55', end: '17:40' },
                { label: '19:00-19:45', start: '19:00', end: '19:45' },
                { label: '19:55-20:40', start: '19:55', end: '20:40' }
            ]);

            // 表格中显示的时间段（含“午休”“晚饭”等非课程时段）
            const timeSlots = ref([
                '08:30-09:15',
                '09:25-10:10',
                '10:30-11:15',
                '11:25-12:10',
                '午休',       // 第4行（索引4）为午休
                '14:00-14:45',
                '14:55-15:40',
                '16:00-16:45',
                '16:55-17:40',
                '晚饭',       // 第9行（索引9）为晚饭
                '19:00-19:45',
                '19:55-20:40'
            ]);

            // ========== 用户与周信息 ==========
            const username = ref('同学'); // 当前登录用户名
            const systemCurrentWeek = ref(1); // 系统认定的“今天”是第几周
            const viewWeek = ref(1);          // 当前页面查看的是第几周
            const baseDate = ref(null);       // 用户设置“今天”时的日期（如 2025-03-03）
            const baseWeek = ref(1);          // 用户设置“今天”对应的周数
            const baseMonday = ref(null);     // 基准周的周一日期（关键！用于计算任意周的日期）

            // 计算当前查看周的日期范围（如 "3/3 - 3/9"）
            const weekDateRange = computed(() => {
                if (!baseMonday.value) return '—';
                const baseMon = new Date(baseMonday.value);
                const offsetWeeks = viewWeek.value - baseWeek.value;
                const monday = new Date(baseMon);
                monday.setDate(monday.getDate() + offsetWeeks * 7);
                const sunday = new Date(monday);
                sunday.setDate(sunday.getDate() + 6);
                const format = (d) => `${d.getMonth() + 1}/${String(d.getDate()).padStart(2, '0')}`;
                return `${format(monday)} - ${format(sunday)}`;
            });

            // 计算表头每天的具体日期（确保周一=真实周一）
            const dayHeaders = computed(() => {
                if (!baseMonday.value) return Array(7).fill('');
                const baseMon = new Date(baseMonday.value);
                const offsetWeeks = viewWeek.value - baseWeek.value;
                const monday = new Date(baseMon);
                monday.setDate(monday.getDate() + offsetWeeks * 7);
                const dates = [];
                for (let i = 0; i < 7; i++) {
                    const d = new Date(monday);
                    d.setDate(d.getDate() + i);
                    dates.push(`${d.getMonth() + 1}/${String(d.getDate()).padStart(2, '0')}`);
                }
                return dates;
            });

            // ========== 课表数据 ==========
            // 初始化 12x7 的二维数组（12个时间段 x 7天），初始值为 null
            const timetable = ref(Array(12).fill().map(() => Array(7).fill(null)));
            const selectedCourse = ref(null); // 当前选中的课程（用于详情弹窗）

            // ========== 表单状态 ==========
            const courseForm = ref({
                name: '',
                teacher: '',
                credit: 0,
                description: '',
                dayOfWeek: 1,     // 1=周一, ..., 7=周日
                timeSlot: '',     // 字符串如 "08:30-09:15"
                location: '',
                weekType: 0       // 0=每周, 1=单周, 2=双周
            });
            const formVisible = ref(false);      // 添加/编辑表单是否显示
            const isEditing = ref(false);        // 是否处于编辑模式
            const editingCourseId = ref(null);   // 正在编辑的课程 ID

            // ========== 设置相关弹窗状态 ==========
            const settingsVisible = ref(false);           // 设置菜单
            const setCurrentWeekVisible = ref(false);     // 设置当前周弹窗
            const selectedCurrentWeek = ref(1);           // 用户选择的当前周
            const viewWeekDialogVisible = ref(false);     // 查看周次弹窗
            const selectedViewWeek = ref(1);              // 用户选择要查看的周

            // ========== 工具函数 ==========
            // 根据开始时间字符串（如 "08:30"）返回在 timeSlots 中的索引
            function getTimeSlotIndex(startTime) {
                if (!startTime) return -1;
                let timeStr = startTime.length > 5 ? startTime.substring(0, 5) : startTime;
                const map = {
                    '08:30': 0, '09:25': 1, '10:30': 2, '11:25': 3,
                    '14:00': 5, '14:55': 6, '16:00': 7, '16:55': 8,
                    '19:00': 10, '19:55': 11
                };
                return map[timeStr] ?? -1;
            }

            // 检查是否时间冲突（同一时段是否已有课程）
            function checkTimeConflict(dayOfWeek, timeSlot) {
                const timeIndex = timeSlots.value.indexOf(timeSlot);
                if (timeIndex === -1) return false;
                const dayIndex = dayOfWeek - 1; // 转为 0~6
                if (dayIndex < 0 || dayIndex > 6) return false;
                const existing = timetable.value[timeIndex]?.[dayIndex];
                // 如果是编辑自己，不算冲突
                if (isEditing.value && existing?.id === editingCourseId.value) return false;
                return existing; // 返回冲突课程或 null
            }

            // ========== API 请求 ==========
            // 从后端加载课表数据（按 viewWeek 加载）
            async function loadTimetable() {
                try {
                    const response = await axios.get('/timetable', {
                        params: { week: viewWeek.value }
                    });
                    if (response.data.success) {
                        const data = response.data;
                        systemCurrentWeek.value = data.systemCurrentWeek;
                        viewWeek.value = data.viewWeek;
                        baseDate.value = data.baseDate;
                        baseWeek.value = data.baseWeek;
                        baseMonday.value = data.baseMonday; // ✅ 关键：获取基准周一

                        // 重建 timetable 二维数组
                        const newTimetable = Array(12).fill().map(() => Array(7).fill(null));
                        data.data.forEach(sc => {
                            const dayIndex = sc.dayOfWeek - 1;
                            const timeIndex = getTimeSlotIndex(sc.startTime);
                            if (dayIndex >= 0 && dayIndex < 7 && timeIndex !== -1) {
                                newTimetable[timeIndex][dayIndex] = sc;
                            }
                        });
                        timetable.value = newTimetable;
                    } else {
                        ElMessage.error(response.data.message || '加载失败');
                    }
                } catch (error) {
                    ElMessage.error('课表加载失败，请重试');
                }
            }

            // ========== 事件处理 ==========
            // 加载用户信息（用户名）
            async function loadUserInfo() {
                try {
                    const res = await axios.get('/user-info');
                    username.value = res.data.username || '同学';
                } catch (e) {
                    username.value = '同学';
                }
            }

            // 打开设置菜单
            function openSettings() {
                settingsVisible.value = true;
            }

            // 处理设置菜单点击
            function handleSetting(action) {
                settingsVisible.value = false;
                switch (action) {
                    case 'add': openAddForm(); break;
                    case 'setWeek': openSetCurrentWeek(); break;
                    case 'logout':
                        if (confirm('确定要切换账号吗？')) {
                            window.location.href = 'login.html';
                        }
                        break;
                }
            }

            // 打开添加课程表单（重置表单）
            function openAddForm() {
                courseForm.value = {
                    name: '', teacher: '', credit: 0, description: '',
                    dayOfWeek: 1, timeSlot: '', location: '', weekType: 0
                };
                isEditing.value = false;
                editingCourseId.value = null;
                formVisible.value = true;
            }

            // 保存课程（新增或编辑）
            async function saveCourse() {
                const { name, dayOfWeek, timeSlot, location } = courseForm.value;
                if (!name?.trim()) return ElMessage.warning('请输入课程名称');
                if (!timeSlot) return ElMessage.warning('请选择上课时间');
                if (!location?.trim()) return ElMessage.warning('请输入上课地点');

                // 检查时间冲突
                const conflict = checkTimeConflict(dayOfWeek, timeSlot);
                if (conflict) return ElMessage.error(`时间冲突！该时段已有课程：${conflict.name}`);

                // 获取时间段对应的 start/end
                const timeItem = timeOptions.value.find(t => t.label === timeSlot);
                if (!timeItem) return ElMessage.error('无效的时间段');

                // 构造提交数据
                const data = { ...courseForm.value, startTime: timeItem.start, endTime: timeItem.end };
                delete data.timeSlot; // 后端不需要 timeSlot 字段
                if (isEditing.value) data.id = editingCourseId.value;

                try {
                    const response = isEditing.value
                        ? await axios.put('/course', data)  // 编辑
                        : await axios.post('/course', data); // 新增
                    if (response.data.success) {
                        ElMessage.success(response.data.message);
                        formVisible.value = false;
                        await loadTimetable(); // 刷新课表
                    } else {
                        ElMessage.error(response.data.message);
                    }
                } catch (error) {
                    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
                }
            }

            // 删除课程
            async function deleteCourse() {
                if (!selectedCourse.value?.id) return;
                try {
                    const response = await axios.delete('/course', { data: { id: selectedCourse.value.id } });
                    if (response.data.success) {
                        ElMessage.success(response.data.message);
                        closeModal();
                        await loadTimetable();
                    } else {
                        ElMessage.error(response.data.message);
                    }
                } catch (error) {
                    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
                }
            }

            // 显示课程详情弹窗
            function showCourseDetail(course) {
                if (!course) return;
                selectedCourse.value = course;
                // 为了在编辑表单中显示正确的时间段，需还原 timeSlot 字段
                const timeLabel = `${course.startTime}-${course.endTime}`;
                courseForm.value = { ...course, timeSlot: timeLabel };
                isEditing.value = true;
                editingCourseId.value = course.id;
                document.getElementById('courseModal').style.display = 'block';
            }

            // 关闭课程详情弹窗
            function closeModal() {
                document.getElementById('courseModal').style.display = 'none';
                selectedCourse.value = null;
            }

            // 从详情页跳转到编辑表单
            function openEditFromDetail() {
                formVisible.value = true;
                closeModal();
            }

            // 打开“设置当前周”弹窗
            function openSetCurrentWeek() {
                selectedCurrentWeek.value = systemCurrentWeek.value;
                setCurrentWeekVisible.value = true;
            }

            // 确认设置当前周（提交到后端）
            async function confirmSetCurrentWeek() {
                try {
                    const response = await axios.post('/week-config', null, {
                        params: { week: selectedCurrentWeek.value }
                    });
                    if (response.data.success) {
                        ElMessage.success('当前周设置成功');
                        setCurrentWeekVisible.value = false;
                        await loadTimetable(); // 重新加载以更新 systemCurrentWeek 和日期
                    } else {
                        ElMessage.error(response.data.message);
                    }
                } catch (error) {
                    ElMessage.error('设置失败: ' + (error.response?.data?.message || error.message));
                }
            }

            // 打开查看周次弹窗
            function openViewWeekDialog() {
                selectedViewWeek.value = viewWeek.value;
                viewWeekDialogVisible.value = true;
            }

            // 确认切换查看周
            function confirmViewWeek() {
                viewWeek.value = selectedViewWeek.value;
                viewWeekDialogVisible.value = false;
                loadTimetable(); // 重新加载对应周的课表
            }

            // 组件挂载后执行
            onMounted(() => {
                loadUserInfo();   // 加载用户名
                loadTimetable();  // 加载课表
            });

            // 暴露给模板使用的响应式数据和方法
            return {
                // 数据
                username,
                systemCurrentWeek,
                viewWeek,
                weekDateRange,
                dayHeaders,
                timetable,
                selectedCourse,
                courseForm,
                timeSlots,
                // 弹窗状态
                formVisible,
                isEditing,
                settingsVisible,
                setCurrentWeekVisible,
                viewWeekDialogVisible,
                selectedCurrentWeek,
                selectedViewWeek,
                // 方法
                openSettings,
                handleSetting,
                openAddForm,
                saveCourse,
                deleteCourse,
                showCourseDetail,
                closeModal,
                openEditFromDetail,
                openSetCurrentWeek,
                confirmSetCurrentWeek,
                openViewWeekDialog,
                confirmViewWeek
            };
        }
    });

    // 安装 Element Plus 插件
    app.use(ElementPlus);
    // 挂载应用
    app.mount('#app');
</script>
</body>
</html>